package com.yckj.activechicken.business.common.controller;

import com.yckj.activechicken.common.constant.Constants;
import com.yckj.activechicken.common.utils.cache.EhCacheUtils;
import com.yckj.activechicken.common.utils.uuid.Base64;
import com.yckj.activechicken.common.utils.uuid.IdUtils;
import com.yckj.activechicken.common.utils.verifycode.VerifyCodeUtils;
import com.yckj.activechicken.framework.web.domain.AjaxResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

/**
 * <p>
 * Title:com.yckj.activechicken.business.controller.common
 * </p>
 * <p/>
 * <p>
 * Description: 描述【验证码处理】
 * </p>
 * <p/>
 * <p>
 * Copyright: Copyright (c) 2019
 * </p>
 * <p/>
 * <p>
 * Company: 英才汇硕信息技术有限公司
 * </p>
 *
 * @author zhoujy
 * @version 1.0
 * @created 2020/5/5 15:31
 */
@RestController
public class CaptchaController {

    /**
     * 生成验证码
     */
    @GetMapping("/captchaImage")
    public AjaxResult getCode(HttpServletResponse response) throws IOException {
        // 生成随机字串
        String verifyCode = VerifyCodeUtils.generateVerifyCode(4);
        // 唯一标识
        String uuid = IdUtils.simpleUUID();
        String verifyKey = Constants.CAPTCHA_CODE_KEY + uuid;

        //120秒失效
        EhCacheUtils.put(verifyKey, verifyCode,120,120);
        // 生成图片
        int w = 111, h = 36;
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        VerifyCodeUtils.outputImage(w, h, stream, verifyCode);
        try {
            AjaxResult ajax = AjaxResult.success();
            ajax.put("uuid", uuid);
            ajax.put("img", Base64.encode(stream.toByteArray()));
            return ajax;
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error(e.getMessage());
        } finally {
            stream.close();
        }
    }
}
